

export function left(a,b) {
    return a.substr(0,b)
}

export function right(a,b) {
    return a.substr(-b)
}

export function char(a) {
    return String.fromCharCode(a)
}

export function fill(a,b) {
    if (typeof (b) == "undefined") b = ' ';
    var result = "";
    for (var i = 0; i < a; i++) {
        result += b;
    }
    return result;
}
// 挑选
// pick()
export function f_pick(a,b) {
    var t = {};
    if (b instanceof Array) {
        b.map(function (prop) {
            t[prop] = a[prop];
        })
    } else {
        for (var prop in b) { t[prop] = a[prop]; }
    }
    return t;
}
export function J(a) {
    return JSON.stringify(a);
}

export function isnull(a,b) {
    if (typeof (b) == "undefined") b = '';
    if (typeof (a) == "undefined") a = '';
    if (a == null) a = '';
    a = a + '';
    if (a.toLowerCase() == 'undefined') a = '';
    if (a.toLowerCase() == 'null') a = '';
    a = a.replace(/(^\s*)|(\s*$)/g,"");
    if (a == '') a = b;
    return a
}

export function sfnull(a,b) {
    if (isnull(a) == "") {
        return true;
    } else {
        return false;
    }
}

// 时间戳
export function timestamp(tm) {
    // tm=tm?new Date(tm):new Date();
    if (tm) {
        tm = tm.replace(/\-/g,'/')
        tm = new Date(tm)
    } else {
        tm = new Date()
    }
    return tm.getTime();
}
export function isnull_obj(a,b) {
    if (typeof (b) == "undefined") b = '';
    if (typeof (a) == "undefined") a = '';
    if (a == null) a = '';
    try { if (JSON.stringify(a) === '{}') a = ''; } catch (error) { }
    if (a == '') a = b;
    return a
}
//  断开变量绑定
export function jj(a) {
    try {
        return JSON.parse(JSON.stringify(a));
    } catch (error) {
        return {}
    }
}

//  重新编排
export function jj2(a) {
    return JSON.stringify(JSON.parse(a));
}

// 对象转数组
export function obj2arr(d) {
    var tmp = [];
    for (var i = 0; i < d.length; i++) {
        tmp.push(d[i]);
    }
    return tmp
}

export function obj2arr_nolenght(d) {
    var tmp = [];
    for (var key in d) {
        //key是属性,object[key]是值
        tmp.push(d[key]); //往数组中放属性
    }
    return tmp
}

export function isarr(o) {
    return Object.prototype.toString.call(o) == '[object Array]';
}

export function isempty(value) {
    return (Array.isArray(value) && value.length === 0) ||
        (Object.prototype.isPrototypeOf(value) && Object.keys(value).length === 0);
}

export function isemptyobject(value) {
    // return Object.keys(value).length==0
    return JSON.stringify(value) === '{}';
    // JSON.stringify(value) === '{}' 空对象判断
}


export function formatTimestamp(timestamp,format) {
    const date = new Date(timestamp);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2,'0');  // 月份从0开始，需加1
    const day = String(date.getDate()).padStart(2,'0');
    const hours = String(date.getHours()).padStart(2,'0');
    const minutes = String(date.getMinutes()).padStart(2,'0');
    const seconds = String(date.getSeconds()).padStart(2,'0');

    // 替换格式字符串中的占位符
    return format
        .replace('yyyy',year)
        .replace('MM',month)
        .replace('dd',day)
        .replace('hh',hours)
        .replace('mm',minutes)
        .replace('ss',seconds);
}



// const timestamp = 1638240000000; // 示例时间戳
// console.log(formatTimestamp(timestamp)); // 输出：2021-11-30 12:00:00

// _date()
// _date(new Date())
// _date(new Date(),"yyyy-MM-dd")
// _date(new Date(),"yyyy-MM-dd hh:mm:ss")
// _date(new Date(),"yyyy-MM-dd hh:mm:ss.S")
export function _date(date,fmt) { //author: meizz
    date = date || (new Date());
    date = new Date(date)
    if (typeof (fmt) == "undefined" || fmt == '') fmt = 'yyyy-MM-dd hh:mm:ss';
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1,(date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1,(RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

export function bmap(ak) {
    return new Promise(function (resolve,reject) {
        if (typeof (BMap) == 'undefined') {
            window.init = function () { resolve(BMap) }
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "http://api.map.baidu.com/api?v=2.0&ak=" + ak + "&callback=init";
            script.onerror = reject;
            document.head.appendChild(script);
        } else {
            resolve(BMap)
        }
    })
}

// import {MP} from '@/map.js'  
// export default {
//     data () {
//       return {
//         ak:'', // 这里就是百度地图密钥
//       }
//     },
//     mounted(){
//       this.$nextTick(function() {
//         var _this = this;
//         MP(_this.ak).then(BMap => {
//           // 百度地图API功能
//         //   ...
//         })
//       })
//     },
// }

// 挑选
// pick()
// tt=pick({t1:1,t2:2,t3:3},['t1','t2'])
// tt=pick({t1:1,t2:2,t3:3},{t1:1,t2:2})
export function pick(a,b) {
    var t = {};
    if (b instanceof Array) {
        b.map(function (prop) {
            t[prop] = a[prop];
        })
    } else {
        for (var prop in b) {
            t[prop] = a[prop];
        }
    }
    return t;
}


export function getquerystring(name) {
    // console.log(decodeURI(window.location.search))
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
    var r = decodeURI(window.location.search).substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return '';
}


export function valid(a,b) {
    if (b) {
        if (b instanceof Array) {
            for (var prop of b) {
                if (isnull(a[prop]) == '') return prop + '为空';
            }
        } else {
            for (var prop in b) {
                var t = b[prop]
                if (isnull(a[prop]) == '') return t.kts ? t.kts : (prop + '为空');
                if (isnull(t.lx) == 'sj') {
                    if (!/(^1[3|4|5|7|8][0-9]{9}$)/.test(isnull(a[prop]))) return t.yzts ? t.yzts : '请输入正确的手机号码';
                }
            }
        }
    } else {
        for (var prop in a) {
            if (isnull(a[prop]) == '') return prop + '为空';
        }

    }
    return '';
}

// ***************************************************************************************************************************************************************************
// app self

// 判断 HH:MM 时间段
export function time_range(beginTime,endTime,varTime) {
    console.log(beginTime)
    console.log(endTime)
    console.log(varTime)
    if (isnull(beginTime,'') == '' || isnull(endTime,'') == '') {
        return true;
    } else {
        if (beginTime < endTime) {
            if (beginTime <= varTime && varTime <= endTime) return true
            else return false
        } else {
            if (!(endTime <= varTime && varTime <= beginTime)) return true
            else return false
        }
        // var strb = beginTime.split (":");  
        // if (strb.length != 2) {  
        //              return false;  
        //       }  
        // var stre = endTime.split (":");  
        // if (stre.length != 2) {  
        //     return false;  
        // }  
        // var strv = varTime.split (":");  
        // if (strv.length != 2) {  
        //     return false;  
        // }  
        // var b = new Date ();  
        // var e = new Date ();  
        // var v=new Date();  
        // b.setHours(strb[0]);  
        // b.setMinutes(strb[1]);  
        // e.setHours(stre[0]);  
        // e.setMinutes(stre[1]);  
        // v.setHours(strv[0]);  
        // v.setMinutes(strv[1]);  
        // if((v.getTime()- b.getTime()>=0 && (e.getTime()- v.getTime())>0)){  
        //     return true;  
        // }else {  
        //     return false;  
        // }  
    }
}


// ***************************************************************************************************************************************************************************
// uniapp
export function nav(url,m) {
    if (url == 'back') {
        if (m) uni.navigateBack({ delta: m });
        else uni.navigateBack();
    } else if (m == 'tab') {
        uni.switchTab({ url });
    } else {
        if (m == 'R') uni.reLaunch({ url });
        else if (m) uni.redirectTo({ url });
        else uni.navigateTo({ url });
    }
    // ,animationType: 'pop-in' 
};

export function storage(key,value) {
    if (typeof (value) == "undefined") {
        let a = '';
        try {
            a = uni.getStorageSync(key) || ''
        } catch (e) { }
        return a
    } else {
        var v = value;
        try {
            uni.setStorageSync(key,value);
        } catch (e) { }
    }
};

export function msg(msg) {
    //  uni.showToast({ title: msg });
    uni.showToast({
        icon: 'none',
        title: msg
    });
};


// 时间戳转年龄
export function _age(timestamp) {
    let currentDate = new Date();
    let birthDate = new Date(timestamp);
    let age = currentDate.getFullYear() - birthDate.getFullYear();
    // 如果用户的生日还没过，年龄减1
    if (currentDate.getMonth() < birthDate.getMonth() ||
        (currentDate.getMonth() === birthDate.getMonth() &&
            currentDate.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}


export const prepage = () => {
    let pages = getCurrentPages();
    let prePage = pages[pages.length - 2];
    // #ifdef H5
    return prePage;
    // #endif
    return prePage;
}

// comfirm('确定要删除么','',res=>{ if (res.confirm) { }else if (res.cancel) { } })

export function getdjbh() {
    var dh = (new Date().getTime()) / 1000
    dh = parseInt((dh + 1004001979) * 1000) + '' + Math.floor(Math.random() * 10) + '' + Math.floor(Math.random() * 10) + '' + Math.floor(Math.random() * 10)
    return dh
};

// 转换省市数据的方法
export function transformProvinceCities(provinceCities) {
    const result = [];
    // 遍历每个省份
    for (const province in provinceCities) {
        const cities = provinceCities[province];
        // 创建省级数据
        const provinceData = {
            text: province,  // 例如 "广东省"
            value: generateProvinceValue(province),  // 生成省份的唯一值
            children: []
        };

        // 遍历每个省份的城市  
        cities.forEach(city => {
            provinceData.children.push({
                text: city,
                value: generateCityValue(city)  // 生成城市的唯一值
            });
        });

        // 将每个省级数据添加到结果中
        result.push(provinceData);
    }

    return result;
};

// 生成省份的值
export function generateProvinceValue(provinceName) {
    const provinceMap = {
        '北京': '110',
        '上海': '120',
        '天津': '130',
        '重庆': '140',
        '河北': '150',
        '山西': '160',
        '内蒙古': '170',
        '辽宁': '180',
        '吉林': '190',
        '黑龙江': '200',
        '江苏': '210',
        '浙江': '220',
        '安徽': '230',
        '福建': '240',
        '江西': '250',
        '山东': '260',
        '河南': '270',
        '湖北': '280',
        '湖南': '290',
        '广东': '300',
        '广西': '310',
        '海南': '320',
        '四川': '330',
        '贵州': '340',
        '云南': '350',
        '西藏': '360',
        '陕西': '370',
        '甘肃': '380',
        '青海': '390',
        '宁夏': '400',
        '新疆': '410'
    };
    return provinceMap[provinceName] || '999';  // 默认值为 '999'
};

// 生成城市的值
export function generateCityValue(cityName) {
    return cityName.replace(/[^\w]/g,'') + '01';  // 假设城市值为去除特殊字符后的城市名加上 '01'
};